package com.samphanie.auiu.biz_detail.biz.goods

import android.graphics.Color
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.core.view.ViewCompat
import androidx.recyclerview.widget.RecyclerView
import com.samphanie.auiu.common.ui.view.loadUrl
import com.samphanie.auiu.pub_mod.model.SliderImage
import com.samphanie.auiu.ui.item.AuiuDataItem
import com.samphanie.auiu.ui.item.AuiuViewHolder

/**
 * 商品相册
 *
 * @author ZSY
 */
class GoodsGalleryItem(val sliderImage: SliderImage) : AuiuDataItem<SliderImage, AuiuViewHolder>() {

    private var parentWith: Int = 0

    override fun onBindData(holder: AuiuViewHolder, position: Int) {
        val imageView = holder.itemView as ImageView
        if (sliderImage.url.isNotBlank()) {
            // 占位图
            // 拿到图片加载后的回调
            // 根据图片的宽高的值，等比计算imageView高度值
            imageView.loadUrl(sliderImage.url) {
                val drawableWidth = it.intrinsicWidth
                val drawableHeight = it.intrinsicHeight

                val params = imageView.layoutParams ?: RecyclerView.LayoutParams(
                    parentWith,
                    RecyclerView.LayoutParams.WRAP_CONTENT
                )
                params.width = parentWith
                params.height = (drawableHeight / (drawableWidth * 1.0f / parentWith)).toInt()
                imageView.layoutParams = params
                ViewCompat.setBackground(imageView, it)
            }
        }
    }

    override fun getItemView(parent: ViewGroup): View? {
        val imageView = ImageView(parent.context)
        imageView.scaleType = ImageView.ScaleType.CENTER_CROP
        imageView.setBackgroundColor(Color.WHITE)
        return imageView
    }

    override fun onViewAttachedToWindow(holder: AuiuViewHolder) {
        // 提前给imageView 预设一个高度值 等于parent的宽度
        parentWith = (holder.itemView.parent as ViewGroup).measuredHeight
        val params = holder.itemView.layoutParams
        if (params.width != parentWith) {
            params.width = parentWith
            params.height = parentWith
            holder.itemView.layoutParams = params
        }
    }
}